package com.fanghaoran.service;

import com.fanghaoran.bean.Interaction;
import com.fanghaoran.dao.SignDao;
import com.fanghaoran.entity.Sign;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: win11
 * @Date: 2023/03/23/13:12
 * @Description: 打卡操作的业务实现层
 */
public class SignService {
    private final SignDao signDao=new SignDao();
    /**
     *实现查询打卡信息
     */
    public Interaction selectSignInfo() throws Exception {
        return signDao.selectSignInfo();
    }
    /**
     *实现更新打卡信息
     */
    public void updateSignInfo(Sign sign) throws Exception {
        signDao.updateSignInfo(sign,isConstant(sign));
    }
    /**
     *实现定时更新数据库中是否打卡的flag标志
     */
    public void updateFlag(Sign sign) throws Exception {
        //获取当前时间
        Date date = new Date();
        //规定日期格式:只获取当前时间的年月日
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //日期类型格式化成字符串
        String dateStr = sdf.format(date);
        //获取时间执行的延迟时间

        long delay = getScheduleTime(dateStr, 0, 0, 0).getTime()-System.currentTimeMillis();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    signDao.updateFlag(sign);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }, delay, TimeUnit.SECONDS);
    }

    /**
     *判断这次打卡是否为连续打卡
     */
    public Boolean isConstant(Sign sign) throws ParseException {
        return new Date().before(getScheduleTime(sign.getLastClockDate().toString(),23,59,59));
    }

    /**
     * 获取指定时间:参数时间的第二天的几时几分几秒
     * @param date 获取时间
     * @return 返回指定时间
     */
    public static Date getScheduleTime(String date,int hour,int minute,int second) throws ParseException {
        //格式化转成日期类型(只获取年月日)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date lastSignTime = sdf.parse(date);
        //调整时间为给定时间的第二天
        lastSignTime.setTime(lastSignTime.getTime()+24*60*60*1000);
        //更改日期格式
        String tomorrowStr = sdf.format(lastSignTime);
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置时间
        String scheduleTimeStr = tomorrowStr + " " + hour + ":" + minute+":"+second;
        //转成日期格式并返回
        return sdf.parse(scheduleTimeStr);
    }
}
